import React from 'react';
import { Breadcrumb, Icon, Button, Table, Modal, Input, Select, Pagination, message ,Row,Col,DatePicker,Form,Checkbox,AutoComplete,InputNumber,Upload ,Switch} from 'antd';
import $ from 'jquery';
import Config from '../../common/config';
import moment from 'moment';
const config = new Config();
const { RangePicker } = DatePicker;
const { TextArea } = Input;
const FormItem = Form.Item;
const Option = Select.Option;
const userInfo = JSON.parse(sessionStorage.getItem('UserInfo')); //用户信息
const root = userInfo.root;

class ChangeNumberInterface extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            visible: false,//我的申请模态框
            replaceWay:1,//换号方式
            record:{},//编辑
            changeNumberList:[],//列表数据(总)
            changeNumberListOn:[],//状态启用列表
            changeNumberListOff:[],//状态关闭列表
            currentstate:1,//筛选状态  1：全部   2：启用  3：停用
            belongedDepartment:undefined,//所属部门
        }
    }
    componentWillMount(){
        let belongedDepartment=undefined;
        if(!root){
            if(userInfo.department.name==="SEM广告部"){
                belongedDepartment='1';
            }else if(userInfo.department.name==="信息流广告部"){
                belongedDepartment='2';
            }else{
                belongedDepartment=undefined;
            }
        }else{
            belongedDepartment=undefined;
        }
        this.setState({
            belongedDepartment,
        })
    }
    componentDidMount() {
        this.getChangeNumberList();
    }
    //banner详细信息对话框（新增/编辑）
    showBannerModal(values) {
        console.log(values);
        if(values){
            this.setState({
                record:values,
                visible: true,
                BannerId: values.id,
            },()=>{
                this.props.form.setFieldsValue({
                    urlname : values.urlname,//链接名称(必填）
                    remark : values.remark,//备注
                    organization : values.organization,//所属组别
                    replaceway :  values.replaceway,//换号方式(必填）
                    wechat : values.wechat,//微信号(必填）
                });
            });
            if(values.replaceway==4){
                this.setState({
                    replaceWay:4,
                },()=>{
                    this.props.form.setFieldsValue({
                        ipcount : values.ipcount,//IP访问次数
                    });
                })
            }
            if(values.replaceway==3) {
                this.setState({
                    replaceWay: 3,
                }, () => {
                    this.props.form.setFieldsValue({
                        numbers: values.numbers ? moment(values.numbers) : undefined,//IP换号设定数量/或定时替换时间
                    })
                });
            }
        } else{
            this.setState({
                record:{},
                visible: true,
                BannerId:undefined
            },()=>{
                this.props.form.setFieldsValue({
                    organization : this.state.belongedDepartment,//所属组别
                });
            });
        }
    }
    //取消，关闭对话框
    handleCancel() {
        this.props.form.resetFields();
        this.setState({
            visible: false,
            replaceWay:1,
        });
    }
    //文件写入函数
    writeFile( host,id, wechat, replaceway, numbers, ipcount,){
        $.ajax({
            url:`${config.juseLittleTool}/wechat/writefile`,
            type: "post",
            async: true,
            headers: {
                'Authorization': 'Bearer ' + sessionStorage.getItem('token'),
            },
            data:{
                host,
                id,
                wechat,//微信号
                replaceway,//换号方式
                numbers,//定时替换时间
                ipcount,//IP访问次数
            },
            success: data => {
                console.log(data);
                if(data.code === 200){}else{
                    Modal.warning({
                        title: '保存失败',
                        content: `${data.mes}请返回重新操作`,
                    });
                }
            }
        });
    }
    //保存
    saveBanner() {
        this.props.form.validateFields((err, values)=>{
            if(!err){
                if(values.numbers){
                    let arr=values.wechat.split(',');
                    let arr1=values.wechat.split(',');
                    if(arr[arr.length-1]===''){
                        arr1=arr.slice(0,arr.length-1);
                    }
                    if(arr1.length!==2){
                        message.error('微信号输入格式不对，请重新输入！',2);
                        return;
                    }else{
                        if(arr1.filter(key=>key!=='').length!==2){
                            message.error('微信号输入格式不对，请重新输入！',2);
                            return;
                        }
                    }
                }
                let numbers=undefined;
                if(values.numbers){
                    numbers=values.numbers.format('YYYY-MM-DD HH:mm:ss')
                }
                const {BannerId} = this.state;
                console.log(values);
                let url,
                    data={
                         urlname : values.urlname,//链接名称(必填）
                         state : 1,//使用状态  1:正常 0:禁用
                         remark : values.remark,//备注
                         organization : values.organization,//所属组别
                         replaceway :  values.replaceway,//换号方式(必填）
                         wechat : values.wechat,//微信号(必填）
                         numbers,//IP换号设定数量/或定时替换时间
                         ipcount : values.ipcount,//IP访问次数
                         // urlexplain : values.urlexplain,//链接推广说明
                    };
                if(BannerId){
                    url = `${config.juseLittleTool}/wechat/update`;
                    data.id = BannerId;
                }else{
                    url = `${config.juseLittleTool}/wechat/save`;
                }
                $.ajax({
                    url: url,
                    type: "post",
                    async: true,
                    headers: {
                        'Authorization': 'Bearer ' + sessionStorage.getItem('token'),
                    },
                    data:data,
                    success: data => {
                        console.log(data);
                        if(data.code === 200){
                            this.setState({
                                visible: false,
                                replaceWay:1,
                            });
                            this.getChangeNumberList();
                            this.props.form.resetFields();
                            this.writeFile(  values.urlname,BannerId?BannerId:data.id[0].id, values.wechat, values.replaceway, numbers, values.ipcount,);
                            message.success('操作成功！',1);
                        }else{
                            Modal.warning({
                                title: '保存失败',
                                content: `${data.mes}请返回重新操作`,
                            });
                        }
                    }
                });
            }else{
                message.error(`请按规定填写信息，再提交`, 2);
            }
        })
    }
    //获取列表
    getChangeNumberList() {
        $.ajax({
            url: `${config.juseLittleTool}/wechat/findlist`,
            type: "post",
            async: true,
            headers: {
                'Authorization': 'Bearer ' + sessionStorage.getItem('token'),
            },
            data:{},
            success: data => {
                console.log(data);
                if (data.code === 200) {
                    const changeNumberList = data.data.rows;
                    let changeNumberListOn=[];
                    let changeNumberListOff=[];
                    if (changeNumberList.length > 0) {
                        changeNumberListOn=changeNumberList.filter(key=>key.state==1);
                        changeNumberListOff=changeNumberList.filter(key=>key.state==0);
                        changeNumberListOn.sort((a,b)=>a.id-b.id);
                        changeNumberListOff.sort((a,b)=>a.id-b.id);
                        this.setState({
                            changeNumberListOn:root?changeNumberListOn:changeNumberListOn.filter(key=>((key.organization==this.state.belongedDepartment)||(key.organization==null))),
                            changeNumberListOff:root?changeNumberListOff:changeNumberListOff.filter(key=>((key.organization==this.state.belongedDepartment||key.organization==null))),

                        },()=>{
                            const{changeNumberListOn,changeNumberListOff}=this.state;
                            this.setState({
                                changeNumberList:changeNumberListOn.concat(changeNumberListOff),
                            });
                            console.log(this.state.changeNumberListOn);
                            console.log(this.state.changeNumberListOff);
                        });
                    }else{
                        this.setState({
                            changeNumberListOn:[],
                            changeNumberListOff:[],
                            changeNumberList:[],
                        });
                    }
                } else {
                    message.error(`${data.mes} 请返回重新操作`, 2);
                }
            }
        });
    }
    //更改状态
    handleChangeState(id,state){
        $.ajax({
            url: `${config.juseLittleTool}/wechat/delete`,
            type: "post",
            async: true,
            headers: {
                'Authorization': 'Bearer ' + sessionStorage.getItem('token'),
            },
            data:{
                id,
                state:state?1:0
            },
            success: data => {
                console.log(data);
                if (data.code === 200) {
                   this.getChangeNumberList();
                   message.success('更新成功',1)
                } else {
                    message.error(`${data.mes} 请返回重新操作`, 2);
                }
            }
        });

    }
    //更改换号方式
    handleChangeReplaceWay(value){
        //换号方式：1: 立即换 2: 随机换 3: 定时换 4: IP数换
        console.log(value);
        if(value==4){
            this.setState({
                replaceWay:4,
            })
        }else if(value==3){
            this.setState({
                replaceWay:3,
            })
        }else{
            this.setState({
                replaceWay:1,
            })
        }
    }
    //日期禁用
    disabledDate1(val) {
        if (val) {
            return val.valueOf() < Date.now();
        } else {
            return false;
        }
    }
    //切换状态
    changeState(){
        let currentstate=this.state.currentstate;
        let nextState=1;
        let arr=[];
        switch(currentstate){
            case 1:
                nextState=2;
                arr=this.state.changeNumberListOn;
                break;
            case 2:
                nextState=3;
                arr=this.state.changeNumberListOff;
                break;
            case 3:
                nextState=1;
                arr=this.state.changeNumberListOn.concat(this.state.changeNumberListOff);
                break;
            default:
                break;
        }
        this.setState({
            changeNumberList:arr,
            currentstate:nextState,
        })
    }
    render() {
        //费用预览表格
        const data = [
            {
                title: '编号',
                dataIndex: 'id',
                width: 100,
            },{
                title: '链接',
                dataIndex: 'urlname',
                width: 120,
                render:(text)=> <a href={text.includes('http')?(text):('http://'+text)} target="_blank">{text}</a>
            },{
                title: '备注',
                dataIndex: 'remark',
                width: 120,
            },{
                title: '微信号',
                dataIndex: 'wechat',
                width: 120,
            },{
                title: '操作',
                width:100,
                render:(text,record)=>record.state==1?<Button type="primary" onClick={this.showBannerModal.bind(this,record)}>换号</Button>:''
            },{
                title: <span style={{cursor:'pointer'}} onClick={this.changeState.bind(this)}>状态<Icon type="filter" /></span>,
                width: 100,
                dataIndex: 'state',
                render:(text,record)=> <Switch checkedChildren="开" unCheckedChildren="关" checked={text==0?false:true} onChange={this.handleChangeState.bind(this,record.id)}/>
            },
        ];
        const { getFieldDecorator } =this.props.form;
        const formItemLayout = { labelCol: { span: 6}, wrapperCol: { span: 16}, };
        const{visible,record,replaceWay,belongedDepartment}=this.state;
        return (
            <div className='goods-label clearfix'>
                {/*面包屑*/}
                < Breadcrumb separator=">" >
                    <Breadcrumb.Item>换号小工具</Breadcrumb.Item>
                    <Breadcrumb.Item>换号管理</Breadcrumb.Item>
                    <Breadcrumb.Item>链接列表</Breadcrumb.Item>
                </Breadcrumb >
                {/*筛选条*/}
                <div style={{marginTop:'40px'}} className="clearfix">
                    <div>
                        <Button type="primary" onClick={this.showBannerModal.bind(this,false)}>新增</Button>
                    </div>
                    <div className='allgoods-table clearfix' style={{marginTop:'40px'}}>
                        <Table
                               rowKey="id"
                               columns={data}
                               dataSource={this.state.changeNumberList}
                               pagination={false}
                               bordered
                        />
                    </div>
                </div>
                <Modal
                    className="banner-modal"
                    title={(JSON.stringify(record)==="{}")?'新增':"编辑"}
                    visible={visible}
                    okText="确定"
                    cancelText="取消"
                    onOk={this.saveBanner.bind(this)}
                    onCancel={this.handleCancel.bind(this)}
                    maskClosable={false}
                >
                    <Form >
                        <FormItem {...formItemLayout} label="链接"  style={{ minHeight: '60px', marginBottom: 0 }}>
                            {getFieldDecorator('urlname', {
                                rules: [{ required: true, message: '请输入链接' }],
                            })(
                                <Input   placeholder="请输入链接" disabled={(JSON.stringify(record)!=="{}")}/>
                            )}
                        </FormItem>
                        <FormItem {...formItemLayout} label="备注"  style={{ minHeight: '60px', marginBottom: 0 }}>
                            {getFieldDecorator('remark', {
                                rules: [{ required: true, message: '请输入备注信息' },
                                    { max: 20, message: '请输入20个字符以内' }],
                            })(
                                <Input  placeholder="请输入20个字符以内备注信息"/>
                            )}
                        </FormItem>
                        <FormItem {...formItemLayout} label="所属组别"  style={{ minHeight: '60px', marginBottom: 0 }}>
                            {getFieldDecorator('organization', {
                                rules: [{ required: true, message: '请选择所属组别' }],
                            })(
                                <Select placeholder="请选择所属组别"
                                        style={{color: (JSON.stringify(record)!=="{}")?'':'rgba(0, 0, 0, 0.65)'}}
                                        disabled={record.organization?true:(JSON.stringify(record)!=="{}")?false:belongedDepartment==1||belongedDepartment==2?true:false}>
                                    <Option value='1' disabled={(JSON.stringify(record)!=="{}")&& (belongedDepartment==2||belongedDepartment==undefined)} >SEM广告部</Option>
                                    <Option value='2' disabled={(JSON.stringify(record)!=="{}")&& (belongedDepartment==1||belongedDepartment==undefined)}>信息流广告部</Option>
                                </Select>
                            )}
                        </FormItem>
                        <FormItem {...formItemLayout} label=" 换号方式"  style={{ minHeight: '60px', marginBottom: 0 }}>
                            {getFieldDecorator('replaceway', {
                                rules: [{ required: true, message: '请选择换号方式' }],
                            })(
                                <Select placeholder="请选择换号方式" onChange={this.handleChangeReplaceWay.bind(this)}>
                                    <Option value='4' >IP</Option>
                                    <Option value='2' >随机</Option>
                                    <Option value='3' >定时切换</Option>
                                    <Option value='1' >立即切换</Option>
                                </Select>
                            )}
                        </FormItem>
                        <FormItem {...formItemLayout} label="微信号"  style={{ minHeight: '60px', marginBottom: 0 }} >
                            {getFieldDecorator('wechat', {
                                    rules: [{ pattern: /^[0-9a-zA-Z,_-]+$/, message: '只能输入英文，数字,下划线，英文横线或英文逗号!' }],
                            })(
                                <TextArea  placeholder={replaceWay===3?'定时切换方式下只能输入2个微信号，并以英文逗号隔开':"请输入微信号，并以英文逗号隔开"}/>
                            )}
                        </FormItem>
                        {replaceWay===4?
                         <FormItem {...formItemLayout} label=" IP数"  style={{ minHeight: '60px', marginBottom: 0 }}>
                            {getFieldDecorator('ipcount', {
                                rules: [{ required: true, message: '请输入IP数' }],
                            })(
                                <InputNumber placeholder="请输入IP数" style={{width:'100%'}} min={0} step={1} precision={0}/>
                            )}
                        </FormItem>:
                            replaceWay===3?
                        <FormItem {...formItemLayout} label=" 时间"  style={{ minHeight: '60px', marginBottom: 0 }}>
                            {getFieldDecorator('numbers', {
                                rules: [{ required: true, message: '请选择时间' }],
                            })(
                                <DatePicker placeholder="请选择时间" showTime format="YYYY-MM-DD HH:mm:ss" disabledDate={this.disabledDate1.bind(this)}/>
                            )}
                        </FormItem>:''}
                    </Form>
                </Modal>
            </div>
        )
    }
}
const ChangeNumberInterfaceForm = Form.create()(ChangeNumberInterface);
export default ChangeNumberInterfaceForm;